<template>
  <lay-form-item label="附件列表" v-if="attments.length > 0">
    <lay-space size="md" class="tip-att">
      <lay-tag closable v-for="(item, index) in attments" @close="handleClose(index, item.id, item.filename)"
        :key="`tag-${index}`" type="primary">{{ item.id }} <a :href="systemConfig.hostURL + item.url"
          :download="item.filename">{{ item.filename }} </a></lay-tag>
    </lay-space>
  </lay-form-item>
  <lay-form-item :label="uplabel" prop="imgurl">
    <lay-col md="8" v-show="false">
      <lay-input v-model="propsAtts"></lay-input>
    </lay-col>
    <div v-permission="PerKey.Upload_Upload">
    <lay-col md="16">
      <lay-upload @done="getUploadFile" :url="systemConfig.uploadUrl" field="File" :data="uploadConfig.uploadFiles"
        :size="configStore.systemConfig.fileSize" :headers="uploadHeaders">
        <template v-slot:default="params">
          <lay-button type="normal" prefix-icon="layui-icon-upload-circle">上传</lay-button>
        </template>
      </lay-upload>
      <span class="tip"> 尺寸：{{ configStore.systemConfig.fileSize }} kb 类型： {{ configStore.systemConfig.fileExt }}</span>
    </lay-col>
  </div>
  </lay-form-item>
</template>

<script lang="ts" setup name="UploadAttments">
import { ref, watch } from "vue";
import { uploadConfig, systemConfig } from "../../library/config"
import { layer } from "@layui/layer-vue";
import { useConfigStore } from "../../store/config";
import { Attment } from "../../types/attment"
import { delOne } from "../../api/module/attment";
import { PerKey } from "../../library/permissionConst"
import { getToken } from '../../library/cookieUtil'
const token = getToken();
const uploadHeaders = { Authorization: "Bearer " + token }

const configStore = useConfigStore() as any;
interface UploadProps {
  modelValue?: string | number,
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  //fileType: Array<String>,
  uplabel?: string,
  attList?: Array<Attment>,
}
const props = withDefaults(defineProps<UploadProps>(), {
  modelValue: undefined,
  uplabel: "上传附件",
  //fileType: () => ['png', 'jpg', 'jpeg'],
  attList: undefined
});

const uplabel = ref(props.uplabel)
const emit = defineEmits(["update:modelValue"])
const propsAtts = ref(props.modelValue) as any
const attments = ref(props.attList) as any

const getUploadFile = (res: any) => {
  let up = JSON.parse(res.data)
  if (up.status == 1) {
    attments.value.push({
      id: up.attPkey,
      filename: up.data.filename,
      url: up.data.url
    })
    if (props.modelValue != null && String(props.modelValue).length > 0) {
      emit('update:modelValue', propsAtts.value += ',' + up.attPkey)
    } else {
      emit('update:modelValue', up.attPkey)
    }
    layer.msg(up.msg)
  } else {
    layer.msg(up.msg, { time: 3000, icon: 2 })
  }
};

watch(
  () => props.modelValue,
  (value) => {
    propsAtts.value = value;
  },
)

watch(
  () => props.attList,
  (value) => {
    attments.value = value
  },
)

const handleClose = (index: number, attid: number, filename: string) => {
  layer.confirm("确认删除ID: " + attid + " " + filename + "  的附件吗？", {
    title: "警告", move: "true", shade: "false", shadeClose: "true",
    btn: [{
      text: '确认', callback: (layerId: number) => {
        delOne(attid).then((res) => {
          if (res.status == 1) {
            let attids = propsAtts.value.toString().split(",")
            attids.splice(attids.indexOf('' + attid + ''), 1).toString()
            emit('update:modelValue', attids.toString())
            attments.value.splice(index, 1);
            layer.msg(res.msg);
          } else {
            layer.msg(res.msg);
          }
          layer.close(layerId);
        })
      }
    }, {
      text: '取消', callback: function (layerId: number) {
        layer.close(layerId);
      }
    }]
  })

};


</script>

<style scoped>
.tip-att {
  line-height: 40px;
  height: 40px;
}

.preview {
  width: 120px;
  height: 80px;
}
</style>